package com.jmb.api.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jmb.api.common.exception.WebApiException;
import com.jmb.api.common.result.ResultCodeEnum;
import com.jmb.api.common.utils.JdbcUtil;
import com.jmb.api.entity.Db;
import com.jmb.api.entity.Role;
import com.jmb.api.vo.Db.DbInfoVO;
import com.jmb.api.vo.Db.DbQueryVO;
import com.jmb.api.web.service.DbService;
import com.jmb.api.web.mapper.DbMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
* @author jin
* @description 针对表【t_db】的数据库操作Service实现
* @createDate 2025-09-25 15:54:58
*/
@Service
public class DbServiceImpl extends ServiceImpl<DbMapper, Db>
    implements DbService{
    @Autowired
    private DbMapper dbMapper;

    @Override
    public void saveOrUpdateDb(Db db) {
        // 判断是更新还是保存
        boolean isUpdate = db.getId() != null;

        // 查询语句
        LambdaQueryWrapper<Db> dbWrapper = new LambdaQueryWrapper<>();
        dbWrapper.eq(Db::getName, db.getName());

        // 判断是修改操作，需要排除当前角色本身
        if (isUpdate){
            dbWrapper.ne(Db::getId, db.getId());
        }
        // 查询是否存在相同名称
        Db selectOne = dbMapper.selectOne(dbWrapper);
        if (selectOne !=null){
            throw new WebApiException(ResultCodeEnum.web_Db_EXIST_ERROR);
        }
        // 执行保存或修改
        super.saveOrUpdate(db);
    }

    @Override
    public IPage<DbInfoVO> ListDb(IPage<DbInfoVO> page, DbQueryVO dbQueryVO) {
        return dbMapper.listDbInfo(page, dbQueryVO);
    }

    @Override
    public String checkDb(Long id,Integer executeId) {
        boolean checked = false;
        Db db = dbMapper.selectById(id);
        if (executeId == 1 ){
             checked = JdbcUtil.checkConnection(db.getUrl(), db.getUsername(), db.getPassword());
        }else if (executeId == 2){
             checked = JdbcUtil.checkConnection(db.getTestUrl(), db.getTestUsername(), db.getTestPassWord());
        }else if (executeId == 3){
             checked = JdbcUtil.checkConnection(db.getDevUrl(), db.getDevUsername(), db.getDevPassword());
        }else if (executeId == 4){
             checked = JdbcUtil.checkConnection(db.getStgUrl(), db.getStgUsername(), db.getStgPassword());
        }else if (executeId == 5){
             checked = JdbcUtil.checkConnection(db.getProdUrl(), db.getProdUsername(), db.getProdPassword());
        }else {
            throw new WebApiException(ResultCodeEnum.getWeb_Db_Code_ERROR);
        }
        if (!checked){
            throw new WebApiException(ResultCodeEnum.SQL_ERROR);
        }


        return "连接成功";

    }
}




